import React from 'react';
import {
  Link,
  Outlet,
  NavLink,
  useSearchParams,
  useLocation
} from 'react-router-dom';
import { getInvoices } from '../mock/data';

//自定义NavLink
function QueryNavLink({ to, ...props }) {
  //获取history对象
  let location = useLocation();
  // console.log(location);
  //{pathname: '/invoices/2001', search: '', hash: '', state: null, key: '33shav6y'}

  return <NavLink to={to + location.search} {...props} />;
}

export default function Invoices() {
  let invoices = getInvoices();
  let [searchParams, setSearchParams] = useSearchParams();

  return (
    <div style={{ display: 'flex' }}>
      <nav style={{ borderRight: '1px solid', padding: '1rem' }}>
        {/* value={searchParams.get('filter') || ''} 有值时才取，没有为空 */}
        <input
          type="text"
          value={searchParams.get('filter') || ''}
          onChange={(e) => {
            let value = e.target.value;
            // 如果存在设置对象filter属性的值为value
            // 如果不存在设置对象为空
            value ? setSearchParams({ filter: value }) : setSearchParams({});
          }}
        />
        {invoices
          .filter((invoice) => {
            let filter = searchParams.get('filter');
            if (!filter) return true;
            let name = invoice.name.toLowerCase();
            return name.includes(filter.toLowerCase());
          })
          .map((invoice) => {
            // NavLink -> 活动链接 -> isActive
            return (
              <QueryNavLink
                to={`/invoices/${invoice.number}?filter=3&name=zhangsan&age=18`}
                key={invoice.number}
                style={({ isActive }) => {
                  return {
                    display: 'block',
                    margin: '1rem 0',
                    color: isActive ? 'red' : ''
                  };
                }}
              >
                {invoice.name}
              </QueryNavLink>
            );
          })}
      </nav>
      {/* 三级路由定义位置 */}
      <Outlet></Outlet>
    </div>
  );
}
